<script setup lang="ts">
import { onMounted, ref } from "vue";
import Phaser from "phaser";
import { MatchScene } from "./matchTwo";

const title = ref("连连看");
const gameboxRef = ref();
let game: Phaser.Game;
let gameWidth = 0;
let gameHeight = 0;
let zoomRatio = 1;

function initGame() {
  // 设置游戏区域的宽度和高度，使用设备的像素比率以适应不同设备
  gameWidth = gameboxRef.value.clientWidth || 351;
  gameHeight = gameboxRef.value.clientHeight || 542;
  gameHeight = gameHeight * window.devicePixelRatio;
  gameWidth = gameWidth * window.devicePixelRatio;
  // 计算缩放比例，用于调整游戏画面大小
  zoomRatio = Number((gameHeight / 542).toFixed(4));

  const config: Phaser.Types.Core.GameConfig = {
    type: Phaser.AUTO,
    width: gameWidth,
    height: gameHeight,
    parent: gameboxRef.value,
    canvasStyle: "width:100%;height:100%",
    backgroundColor: 0x291f61,
    scene: [
      // Phaser.Scene的三个生命周期：preload,create,update
      new MatchScene(
        { key: "MatchScene" },
        { zoomRatio, gameWidth, gameHeight }
      ),
    ],
    render: {
      // 禁用像素艺术渲染
      pixelArt: false,
      // 启用抗锯齿
      antialias: true,
      // 禁用像素对齐
      roundPixels: false,
      // 在每次渲染前清除画布
      clearBeforeRender: true,
      // 如果性能不佳则不创建WebGL上下文
      failIfMajorPerformanceCaveat: false,
      // 设置WebGL上下文的优先级为默认
      powerPreference: "default",
    },
    scale: {
      // 设置缩放模式为根据父容器大小调整
      mode: Phaser.Scale.RESIZE,
      // 设置父容器为gameboxRef引用的元素
      parent: gameboxRef.value,
      // 设置游戏画布宽度为父容器的100%
      width: "100%",
      // 设置游戏画布高度为父容器的100%
      height: "100%",
      // 设置游戏画布在父容器中水平和垂直居中
      autoCenter: Phaser.Scale.CENTER_BOTH,
    },
  };

  game = new Phaser.Game(config);
}

onMounted(() => {
  initGame();
});
</script>

<template>
  <div class="container flex-center flex-col">
    <h1>{{ title }}</h1>
    <div ref="gameboxRef" class="gamebox"></div>
  </div>
</template>

<style scoped lang="less">
.gamebox {
  width: 80%;
  height: 80%;
  position: relative;
  overflow: hidden;
  background-color: transparent;
}
</style>